package com.leaves.javamall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.leaves.common.constant.ProductConstant;
import com.leaves.javamall.product.dao.AttrAttrgroupRelationDao;
import com.leaves.javamall.product.dao.AttrGroupDao;
import com.leaves.javamall.product.dao.CategoryDao;
import com.leaves.javamall.product.entity.AttrAttrgroupRelationEntity;
import com.leaves.javamall.product.entity.AttrGroupEntity;
import com.leaves.javamall.product.entity.CategoryEntity;
import com.leaves.javamall.product.service.CategoryService;
import com.leaves.javamall.product.vo.AttrGroupRelationVo;
import com.leaves.javamall.product.vo.AttrRespVo;
import com.leaves.javamall.product.vo.AttrVo;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leaves.common.utils.PageUtils;
import com.leaves.common.utils.Query;

import com.leaves.javamall.product.dao.AttrDao;
import com.leaves.javamall.product.entity.AttrEntity;
import com.leaves.javamall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        this.save(entity);
        //保存分组关系
        if(attr.getAttrType() == ProductConstant.attrType.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity aarEntity = new AttrAttrgroupRelationEntity();
            aarEntity.setAttrGroupId(attr.getAttrGroupId());
            aarEntity.setAttrId(entity.getAttrId());
            attrAttrgroupRelationDao.insert(aarEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long attrId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type)?ProductConstant.attrType.ATTR_TYPE_BASE:ProductConstant.attrType.ATTR_TYPE_SALE.getCode());
        //根据不同情况封装不同条件
        if (attrId != 0) { //传入数据不为0 我们要进行判断
            queryWrapper.eq("catelog_id", attrId); //查找指定的分类属性
        }//参数为0的时候，我们不拼接任何条件
        String key = (String) params.get("key");
        //判断是否带有查找关键字
        if (!StringUtils.isNullOrEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        //查找符合指定条件的数据 返回page
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        //添加查询catelogName和groupName
        PageUtils pageUtils = new PageUtils(page);
        //获得查找出的记录
        List<AttrEntity> records = page.getRecords();
        //使用stream过滤找到我们需要的数据
        List<AttrRespVo> respVoList = records.stream().map((attrEntity) -> {//映射查到的表格中的Entity数据
            AttrRespVo attrRespVo = new AttrRespVo();
            //使用BeanUtails获得attrEntity中的基础属性
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //添加attrEntity中不具有的分类和分组名字

            //判断如果type是base 我们就不设置groupname
            if ("base".equalsIgnoreCase(type)) {
                //从中间表中找到属性id
                AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                //利用属性id 在属性表中找到对应的记录
                if (attr_id != null) {
                    attrRespVo.setAttrGroupId(attr_id.getAttrGroupId());
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
//                System.out.println("attrGroupEntity: "+ attrGroupEntity);
                    if (attrGroupEntity != null) {//在设置前一定要加上非空判断！
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }


            //查询分类信息
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        //封装到respVolist中
        pageUtils.setList(respVoList);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(byId, attrRespVo);

        if(byId.getAttrType() == ProductConstant.attrType.ATTR_TYPE_BASE.getCode()) {
            //分组信息
            AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attr_id != null && attr_id.getAttrGroupId() != null) {
                attrRespVo.setAttrGroupId(attr_id.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //分类信息
        Long catelogId = byId.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrRespVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);

        this.updateById(attrEntity);
        //判断是基础属性还是销售属性
        if (attrEntity.getAttrType() == ProductConstant.attrType.ATTR_TYPE_BASE.getCode()) {
            //修改关联表中的信息
            AttrAttrgroupRelationEntity aagEntity = new AttrAttrgroupRelationEntity();
            aagEntity.setAttrGroupId(attr.getAttrGroupId());
            aagEntity.setAttrId(attr.getAttrId());


            Integer attr_id = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (attr_id > 0) {
                attrAttrgroupRelationDao.update(aagEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(aagEntity);
            }
        }
    }

    //根据分组ID查找关联的属性
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> attrGroupEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        if(attrGroupEntityList == null || attrGroupEntityList.size()==0){
            return null;
        }
        List<Long> attrIds = attrGroupEntityList.stream().map((entity) -> {
            return entity.getAttrId();
        }).collect(Collectors.toList());
        List<AttrEntity> attrEntities = this.listByIds(attrIds);
         return attrEntities;
    }

    @Override
    public void deleteRealtion(AttrGroupRelationVo[] vos) {
//     attrAttrgroupRelationDao.delete(new QueryWrapper<>().eq("attr_id",1L).eq("attr_group_id"),1L);
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, entity);
            return entity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(entities);
    }

    //获取当前分组没有关联的属性
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1。当前分组只能关联自己所属分类里面的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2。当前分组只能关联别的分组没有引用的属性
        //1).找到当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //2).找到这些分组关联的属性

        List<AttrAttrgroupRelationEntity> groupId = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //3).从当前分类的所有属性中移除属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.attrType.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmptyOrWhitespaceOnly(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

}